import Entity from './entity'
import { genIdSelector } from './genIdInSelector'

export default class Plan extends Entity {
    constructor(db) {
        super(db, 'plans')
    }

    async getAllPlanSummaries() {
        const result = await this.find({}, { sort: { create_at: -1 }, limit: 20, project: { suites: 0 }, addFields: { suiteIds: '$suites.id' } })
        return result.map(item => ({ ...item, suites: [] }))
    }

    async getAllSuitesOfPlan(planId) {
        const plans = await this.find(genIdSelector(planId))
        return plans && plans.length ? plans[0].suites.map(suite => {
            suite.stepList = []
            return suite
        }) : []
    }

    async getAllStepsOfSuiteInPlan({ planId, suiteId }) {
        const plans = await this.find(genIdSelector(planId))

        if (plans && plans.length) {
            const suite = plans[0].suites.find(suite => suite.id === suiteId)
            return suite ? suite.stepList : []
        } else {
            return []
        }
    }

    async getAllStepCountOfPlan({ planId }) {

        const stepListCount = await this.aggregate([
            {
                '$match': genIdSelector(planId)
            }, {
                '$project': {
                    'suites': 1
                }
            }, {
                '$unwind': {
                    'path': '$suites'
                }
            }, {
                '$addFields': {
                    'suiteId': '$suites.id'
                }
            }, {
                '$addFields': {
                    'stepListCount': {
                        '$size': '$suites.stepList'
                    }
                }
            }, {
                '$project': {
                    'suiteId': 1,
                    'stepListCount': 1
                }
            }
        ])

        return stepListCount.reduce((result, current) => {
            result[current.suiteId] = current.stepListCount
            return result
        }, {})
    }
}